#   Copyright 2006 Jerome Lacoste (jerome@coffeebreaks.org)
#
#   Licensed under the Apache License, Version 2.0 (the "License");
#   you may not use this file except in compliance with the License.
#   You may obtain a copy of the License at
#
#       http://www.apache.org/licenses/LICENSE-2.0
#
#   Unless required by applicable law or agreed to in writing, software
#   distributed under the License is distributed on an "AS IS" BASIS,
#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#   See the License for the specific language governing permissions and
#   limitations under the License.
class Project < ActiveRecord::Base

  belongs_to :client
  has_many :worklogs, :through => :assignments

  has_many :assignments
  has_many :assignees, :class_name => "User", :through => :assignments, :source => :user

  validates_presence_of :short, :name, :client_id
  validates_uniqueness_of :short

  def before_create
    self.short = self.short.upcase
  end

  # Find the projects a specific user is assigned to
  # note we have user :has_many :through, but that doesn't work with sorting...
  def self.find_assigned_to_user(user_id, order = "short asc")
    Project.find(:all,
                 :select => "projects.*",
                 :joins => "LEFT OUTER JOIN assignments a ON projects.id = a.project_id",
                 :conditions => "a.user_id = #{user_id}",
                 :order => order)
  end

  # Find the projects a specific user is assigned to
  # note we have user :has_many :through, but that doesn't work with sorting...
  def self.find_owned_by_user(user_id, order = "short asc")
    Project.find(:all,
                 :select => "projects.*",
                 :joins => "LEFT OUTER JOIN clients c ON projects.client_id = c.id",
                 :conditions => "c.owner_id = #{user_id}",
                 :order => order)
  end

  def issue_tracker
    client.issue_tracker
  end

end
